package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {
    @Autowired
    private EmpService empService;
    @Autowired
    private DeptService deptService;

    @GetMapping
    public Result page(EmpQueryParam param) {
        log.info("员工列表查询条件：{}", param);
        // 调用Service层查询分页数据
        //调用前记得先传入config配置 从mybatis-plus官网中找
        //new 一个苞米豆的page 需要传入对相对于实体类操作的泛型,
        //记得Mapper层实现baseMapper<Emp>以及service层继承Iservice<Emp> serviceImpl 继承苞米豆中ServiceImpl<EmpMapper,Emp>
        Page<Emp> empPage = new Page<>(param.getPage(), param.getPageSize());
        //调用分页中的排序方法.是一个静态的方法 根据update_time 倒序
        empPage.addOrder(OrderItem.desc("update_time"));

        LambdaQueryWrapper<Emp> lqw = new LambdaQueryWrapper<>();
        //select * from emp where name like ? and gender = ? and entrydate between ? and ?
        lqw.like(param.getName()!=null&&param.getName().length()>0,Emp::getName,param.getName());
        lqw.eq(param.getGender()!=null,Emp::getGender,param.getGender());
        lqw.between(param.getBegin()!=null&&param.getEnd()!=null,Emp::getEntryDate,param.getBegin(),param.getEnd());


        //service层调用page方法查询数据,把苞米豆page扔进去
        empPage = empService.page(empPage,lqw);

        List<Emp> emp = empPage.getRecords();
        //拿到page后获取他的total和records  Objects::nonNull
        Set<Integer> idSet = emp.stream().map(Emp::getDeptId).filter(Objects::nonNull).collect(Collectors.toSet());
        if (idSet!=null && idSet.size()>0){
            List<Dept> depts = deptService.listByIds(idSet);
            /*for (Emp emp1 : emp) {
                for (Dept dept : depts) {
                    if (emp1!=null&&emp1.getDeptId()!=null&&dept!=null&&emp1.getDeptId().equals(dept.getId())){
                        emp1.setDeptName(dept.getName());
                    }
                }
            }*/
            Map<Integer, String> map = depts.stream().collect(Collectors.toMap(Dept::getId, Dept::getName));
            for (Emp emp1 : emp) {
                emp1.setDeptName(map.get(emp1.getDeptId()));
            }
        }




        PageResult<Emp> page =  new PageResult<Emp>(empPage.getTotal(),emp);

        // 返回结果
        return Result.success(page);
    }

    @PostMapping
    public Result save(@RequestBody Emp emp) {
        log.info("新增员工，员工信息：{}", emp);

        boolean result = empService.saveEmp(emp);
        // 调用service层方法保存员工信息和员工的工作经历信息


        return Result.success();
    }

    @DeleteMapping
    public Result delete(@RequestParam List<Integer> ids) {
        log.info("批量删除学生，{}", ids);

        empService.removeEmpByIds(ids);
        // 调用service层方法批量删除员工信息和员工工作经历信息

        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        log.info("根据ID查询员工信息，id：{}", id);
        Emp empById = empService.getEmpById(id);
        return Result.success(empById);
    }

    @PutMapping
    public Result update(@RequestBody Emp emp) {
        log.info("修改员工信息，员工信息：{}", emp);

        boolean result = empService.updateEmpById(emp);
        // 调用service层方法修改员工信息
        return Result.success(result);
    }

    @GetMapping("/list")
    public Result list() {
        log.info("查询员工列表");

        // 调用service层方法查询员工列表
        return Result.success();
    }
}
